package org.springframework.samples.mvc.basic.model;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;

public class ReflectionModel<T extends Identifiable> implements UIFormModel {

	private Class<T> type;
	private List<String> excludedFields;

	public ReflectionModel(Class<T> type, String... excludedFields) {
		this.type = type;
		this.excludedFields = Arrays.asList(excludedFields);
	}

	public int getNumberOfColumns() {
		return getFieldNames().length;
	}

	public String[] getFieldLabels() {
		final List<String> fields = new ArrayList<String>();
		FieldCallback fc = new FieldCallback() {
			public void doWith(Field field) throws IllegalArgumentException,
					IllegalAccessException {
				String fieldName = field.getName();
				if (excludedFields.contains(fieldName)) {
					return;
				}
				fields.add(fieldName);
			}
		};
		ReflectionUtils.doWithFields(type, fc );
		return fields.toArray(new String[fields.size()]);
	}

	public String[] getFieldNames() {
		final List<String> fields = new ArrayList<String>();
		FieldCallback fc = new FieldCallback() {
			public void doWith(Field field) throws IllegalArgumentException,
					IllegalAccessException {
				String fieldName = field.getName();
				if (excludedFields.contains(fieldName)) {
					return;
				}
				fields.add(fieldName);
			}
		};
		ReflectionUtils.doWithFields(type, fc );
		return fields.toArray(new String[fields.size()]);
	}

	public String getModelAttribute() {
		return type.getSimpleName().substring(0, 1).toLowerCase() + type.getSimpleName().substring(1);
	}

//	public Object getId(int row) {
//		return objects.get(row).getId();
//	}
	
	protected Class<T> getType() {
		return type;
	}

}
